package 死锁;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DeadLockSample extends Thread{
    private String first;
    private String second;
    public DeadLockSample(String name,String first,String second){
        super(name);
        this.first=first;
        this.second=second;
    }

    @Override
    public void run() {
        synchronized (first){
            System.out.println(Thread.currentThread().getName()+"获得资源："+this.first);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (second){
                System.out.println("获得资源："+this.second);
            }
        }
    }

//    public static void main(String[] args) throws InterruptedException {
//        DeadLockSample d1=new DeadLockSample("A","first","second");
//        DeadLockSample d2=new DeadLockSample("B","second","first");
//        d1.start();
//        d2.start();
//        d1.join();
//        d2.join();
//    }
public static void main(String[] args) throws InterruptedException {

        //可利用ThreadMXBean进行死锁扫描
    ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
    Runnable dlCheck = new Runnable() {

        @Override
        public void run() {
            long[] threadIds = mbean.findDeadlockedThreads();
            if (threadIds != null) {
                ThreadInfo[] threadInfos = mbean.getThreadInfo(threadIds);
                System.out.println("Detected deadlock threads:");
                for (ThreadInfo threadInfo : threadInfos) {
                    System.out.println(threadInfo.getThreadName());
                }
            }
        }
    };

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    // 稍等 5 秒，然后每 10 秒进行一次死锁扫描
    scheduler.scheduleAtFixedRate(dlCheck, 5L, 10L, TimeUnit.SECONDS);
// 死锁样例代码…
    DeadLockSample d1=new DeadLockSample("A","first","second");
    DeadLockSample d2=new DeadLockSample("B","second","first");
    d1.start();
    d2.start();
}
}
